package com.sichemxiang.config.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public Map<String, Object> handleNoHandlerFoundException(NoHandlerFoundException ex) {
        logger.error("No handler found exception occurred", ex); // 记录异常日志
        Map<String, Object> response = new HashMap<>();
        response.put("code", "404");
        response.put("message", ErrorConstants.NOT_FOUND_ERROR_MESSAGE);
        return response;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> handleException(Exception ex) {
        logger.error("An unexpected exception occurred", ex); // 记录异常日志
        Map<String, Object> response = new HashMap<>();
        response.put("code", "500");
        response.put("message", ErrorConstants.INTERNAL_SERVER_ERROR_MESSAG);
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> handleBaseException(BaseException ex) {
        logger.error("BaseException occurred", ex); // 记录异常日志
        Map<String, Object> response = new HashMap<>();
        response.put("code", ex.getCode());
        response.put("message", ex.getMessage());
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
//        if ("10000".equals(ex.getCode())) {
//            status = HttpStatus.OK;
//        } else if ("100001".equals(ex.getCode())) {
//            status = HttpStatus.INTERNAL_SERVER_ERROR;
//        }

        return new ResponseEntity<>(response, status);

    }
}